package model;

import java.util.Hashtable;

import javax.swing.table.AbstractTableModel;

/*
 * Repräsentiert Daten in der JTable der CustomerView
 * Wird aktualisiert, sobald sich etwas am ModelShop ändert
 */

public class MyTableModel extends AbstractTableModel {
	private String[] columnNames = { "Name", "Price", "MaxCount", "OrderCount" };
	private ModelShop modelShop;
	// private List<Integer> orderCount = new ArrayList<>();
	private Hashtable<Product, Integer> orderMap;

	public MyTableModel(ModelShop modelShop) {
		this.modelShop = modelShop;

		orderMap = new Hashtable<>();
		for (fpt.com.Product p : modelShop.getProductList()) {
			orderMap.put((Product) p, 0);
		}

	}

	@Override
	public int getRowCount() {
		return modelShop.getProductList().size();
	}

	@Override
	public int getColumnCount() {
		return 4;
	}

	@Override
	public void setValueAt(Object value, int row, int col) {
		if (col == 3) {
			if (value instanceof Integer) {
				orderMap.put((Product) modelShop.getProductList().get(row), (Integer) value);
			} else if (value instanceof String) {
				orderMap.put((Product) modelShop.getProductList().get(row),
						Integer.parseInt((String) value));
			} else {
				System.out.println("setValueAt - Value für Row 3 muss int oder String sein!");
			}
		}
		this.fireTableCellUpdated(row, col);
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {

		switch (columnIndex) {
		case 0:
			return modelShop.getProductList().get(rowIndex).getName();
		case 1:
			return modelShop.getProductList().get(rowIndex).getPrice();
		case 2:
			return modelShop.getProductList().get(rowIndex).getQuantity();
		default:
			if ((orderMap.get(modelShop.getProductList().get(rowIndex)) == null)) {
				return 0;
			} else {
				return orderMap.get(modelShop.getProductList().get(rowIndex));
			}
		}
	}

	@Override
	public String getColumnName(int columnIndex) {
		return columnNames[columnIndex];
	}

	@Override
	public boolean isCellEditable(int row, int column) {
		if (column == 3) {
			// Nur OrderCount soll editierbar sein
			return true;
		} else {
			return false;
		}
	}

}
